package oceanlife;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;


public class db {
	/*private static Connection db;
	private static String buffer;
	private static int maxBufferSize = 1;
	private static int bufferSize = 0;
	private static BufferedWriter logFile;
	
	public static void init(){
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			db = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "password");
			buffer = newSQLLogInsert();
			FileWriter fstream = new FileWriter("log.txt");
		    logFile = new BufferedWriter(fstream);

			statusInit();
		} catch(Exception e) {
			System.err.println("Exception: " + e.getMessage());
		}
		statusInit();
	}
	
	private static void statusInit(){
		ResultSet whatever = exec("UPDATE `ocean_life`.`misc_hash` SET `value`='0' WHERE `key`='stopping';");
		whatever = exec("UPDATE `ocean_life`.`misc_hash` SET `value`='1' WHERE `key`='stopped';");
	}
	
	private static String newSQLLogInsert(){
		return "INSERT INTO `ocean_life`.`sim_log` (`run`, `config`, `cycle`, `agent`, `xcoord`, `ycoord`) VALUES";
	}
	
	public static void flushLogBuffer(){
		if(bufferSize > 0){
			System.out.println(bufferSize+" "+buffer);
			//exec(buffer+";");
			buffer = newSQLLogInsert();
			bufferSize = 0;
		}
	}
	
	public static void logInsert(String SQLValues){
	    try {
			logFile.write(SQLValues+"\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
		//if(bufferSize > 0){
		//	buffer += ", ";
		//}
		//buffer += SQLValues;
		//bufferSize++;
		//if(bufferSize >= maxBufferSize){
			//System.out.println(bufferSize+" "+buffer);
			//flushLogBuffer();
		//}
	}
	
	public static ResultSet exec(String SQLQuery){
	    try {
	    	System.out.println(SQLQuery);
	    	PreparedStatement configStatement = db.prepareStatement(SQLQuery);
	    	if(SQLQuery.substring(0, 6).toUpperCase().equals("SELECT")){
	    		return configStatement.executeQuery();
	    	} else {
	    		configStatement.executeUpdate(SQLQuery);
	    		return null;
	    	}
	    } catch (MySQLIntegrityConstraintViolationException eNormal){
	    	
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}*/
}
